//
//  HD_HSP_Messages_ViewController.m
//  HDLiaoNingMeseum
//
//  Created by HDHaoShaoPeng on 2017/8/7.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

#import "HD_HSP_Messages_ViewController.h"
#import "HD_HSP_BroadcastDetail_ViewController.h"
#import "HD_HSP_Broadcast.h"

@interface HD_HSP_Messages_ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;


@property (strong,nonatomic) NSIndexPath *myIndexPath;
@property (strong,nonatomic) NSMutableArray *allArray;
@property (strong,nonatomic) UILabel *noNewLabel;
@property (strong,nonatomic) UIButton *rightButton;
@end

static HDDeclare *declare;
@implementation HD_HSP_Messages_ViewController
@synthesize allArray;


- (void)awakeFromNib
{
    [super awakeFromNib];
    declare = [HDDeclare sharedDeclare];
    self.myIndexPath = nil;
    
    
}

- (IBAction)delegateButtonClicked:(id)sender {
    [self startDelete];
}

- (IBAction)backClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}
- (void)viewDidLoad{
    [super viewDidLoad];
    
    declare = [HDDeclare sharedDeclare];
    
    self.titleLabel.text = declare.informationNewNotice;
    self.titleLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:18.0];
    
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    _tableView.separatorColor = [UIColor grayColor];
    _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView setEditing:NO];
    
    _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightButton.frame = CGRectMake(0.0, 0.0, 45.0, 25.0);
    [_rightButton setImage:[UIImage imageNamed:@"message_delete"] forState:UIControlStateNormal];
    [_rightButton addTarget:self action:@selector(startDelete) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButtonItem =[[UIBarButtonItem alloc]initWithCustomView:_rightButton];
    [self.navigationItem setRightBarButtonItem:rightButtonItem];
    
    //接口获取数据
    [self getDataFromServer];
}
#pragma mark --------- 刷新页面
-(void)fetchNews{
    NSArray *array = [declare giveMeNewsData];
    
    [self.allArray removeAllObjects];
    self.allArray = nil;
    allArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (int i = 0; i<[array count]; i++)
    {
        HD_HSP_Broadcast *temp =[array objectAtIndex:i];
        [self.allArray addObject:temp];
    }
    
    if (self.allArray.count == 0)
    {
        [self tipLabelRelease];
        _noNewLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 100)];
        _noNewLabel.text = declare.noMessage;
        _noNewLabel.textAlignment = NSTextAlignmentCenter;
        _noNewLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:18.0];
        _noNewLabel.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_noNewLabel];
        _rightButton.enabled = NO;
    }
    else
    {
        [self tipLabelRelease];
        _rightButton.enabled = YES;
    }
    //刷新数据
    [self.tableView reloadData];
}
#pragma mark --------- 设置为已读或者删除（1已读2删除）
- (void)setNewsReadedOrDelete:(HD_HSP_Broadcast*)brodcast andType:(NSString*)type{
    //接口
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],HTTP_setReadedOrDelete];
    NSDictionary *params = @{@"device_id":[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:kFirst_Machine_ID]],
                             @"language":[NSNumber numberWithInt:declare.languageType],
                             @"notice_id":brodcast.identifier,
                             @"type":type};
    
    [HD_LY_NetHelper requestWithType:POST withUrl:urlStr withParams:params toShowVC:self success:^(id response) {
        //
        NSDictionary *responseDict = (NSDictionary *)response;
        NSLog(@"收到字典是%@",responseDict);
        if ([[responseDict objectForKey:@"status"] intValue]==1){
            if ([type isEqualToString:@"2"]) {
                [LCCoolHUD showSuccess:@"删除成功" zoom:self.view shadow:YES];
            }
            
        }else if ([responseDict[@"status"] intValue] == 0) {
            [LCCoolHUD showFailure:responseDict[@"msg"] inView:self.view zoom:YES shadow:NO];
        }
        
    } fail:^(NSError *error) {
        //
    } showHUD:NO isCache:NO];
}
#pragma mark --------- 获取资讯
- (void)getDataFromServer{
    //接口
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[HDDeclare IP_Request_Header],HTTP_getNewsList];
    NSDictionary *params = @{@"device_id":[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:kFirst_Machine_ID]],
                             @"language":[NSNumber numberWithInt:declare.languageType]};
    
    [HD_LY_NetHelper requestWithType:POST withUrl:urlStr withParams:params toShowVC:self success:^(id response) {
        //
        NSDictionary *responseDict = (NSDictionary *)response;
        NSLog(@"收到字典是%@",responseDict);
        if ([responseDict allKeys].count>0&&[[responseDict objectForKey:@"status"] intValue]==1){
            NSArray *dataA = [responseDict objectForKey:@"data"];
            if (dataA.count>0) {
                [self initDataArrayWith:dataA];
            }
            
        }else if ([responseDict[@"status"] intValue] == 0) {
            [LCCoolHUD showFailure:responseDict[@"msg"] inView:self.view zoom:YES shadow:NO];
        }
        
    } fail:^(NSError *error) {
        //
    } showHUD:NO isCache:NO];
}

- (void)initDataArrayWith:(NSArray*)array{
    for (int i=0;i<array.count; i++) {
        NSDictionary *dic = [array objectAtIndex:i];
        
        HD_HSP_Broadcast *news = [[HD_HSP_Broadcast alloc] init];
        news.identifier = [dic objectForKey:@"zixun_id"];
        news.title = [dic objectForKey:@"title"];
        news.time = [dic objectForKey:@"time"];
        news.content = [dic objectForKey:@"desc"];
        news.html_path = [dic objectForKey:@"html_path"];
        news.list_img = [dic objectForKey:@"list_img"];
        if ([[dic objectForKey:@"is_read"] intValue]==1) {
            news.status = @"old";
        }else{
            news.status = @"new";
        }
        
        [declare addANewWith:news];
    }
    //
    [self fetchNews];
}


#pragma mark - ------ TalbeView Delegate Methods --------

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.allArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"newsCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell)
    {
        cell = nil;
    }
    cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    
    HD_HSP_Broadcast *item = [self.allArray objectAtIndex:indexPath.row];
    
    //img
    UIImageView *cellImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 100, 70)];
    [cellImg sd_setImageWithURL:[NSURL URLWithString:item.list_img] placeholderImage:[UIImage imageNamed:@"message"]];
    [cell.contentView addSubview:cellImg];
    //title
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(cellImg.frame.origin.x+cellImg.frame.size.width+10, 0, ScreenWidth-(cellImg.frame.origin.x+cellImg.frame.size.width+20), 40)];
    titleLabel.numberOfLines = 0;
    titleLabel.text = item.title;
    titleLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:15.0];
    [cell.contentView addSubview:titleLabel];
    //content
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(cellImg.frame.origin.x+cellImg.frame.size.width+10, 30, ScreenWidth-(cellImg.frame.origin.x+cellImg.frame.size.width+20), 40)];
    contentLabel.numberOfLines = 0;
    contentLabel.text = item.content;
    contentLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:12.0];
    [cell.contentView addSubview:contentLabel];
    
    //select bg
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cell_selected"]];
    cell.selectedBackgroundView = image;
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.myIndexPath = indexPath;
    return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //设置为已读
    HD_HSP_Broadcast *temp = [self.allArray objectAtIndex:indexPath.row];
    if ([temp.status isEqualToString:@"new"]) {
        [self setNewsReadedOrDelete:temp andType:@"1"];
    }
    
    temp.status = @"old";
    [declare makeSeenWith:temp.identifier];
    
    [self performSegueWithIdentifier:@"pushToNewsDetailLine" sender:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    HD_HSP_Broadcast *item = [self.allArray objectAtIndex:self.myIndexPath.row];
    HD_HSP_BroadcastDetail_ViewController *vc = (HD_HSP_BroadcastDetail_ViewController *)segue.destinationViewController;
    vc.item = item;
}


#pragma mark - ------- Delete Methods --------

- (void) startDelete
{
    BOOL editOrNot = self.tableView.editing;
    [self.tableView setEditing:!editOrNot animated:YES];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        HD_HSP_Broadcast *model = self.allArray[indexPath.row];
        [declare delegateNewsWith:model.identifier];
        
        //删除
        [self setNewsReadedOrDelete:model andType:@"2"];
        
        [self.allArray removeObjectAtIndex:indexPath.row];
        
        [self.tableView reloadData];
        
        BOOL state = YES;
        if (self.allArray.count == 0)
        {
            state = NO;
            [self tipLabelRelease];
            _noNewLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 100)];
            _noNewLabel.text = declare.noMessage;
            _noNewLabel.textAlignment = NSTextAlignmentCenter;
            _noNewLabel.font = [UIFont fontWithName:@"FZQKBYSJW--GB1-0" size:18.0];
            _noNewLabel.backgroundColor = [UIColor clearColor];
            [self.view addSubview:_noNewLabel];
        }
        else
        {
            [self tipLabelRelease];
        }
        [self.navigationItem.rightBarButtonItem setEnabled:state];
    }
}

- (void)tipLabelRelease
{
    if (_noNewLabel != nil)
    {
        [_noNewLabel removeFromSuperview];
        self.noNewLabel = nil;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return declare.deleteNews;
}

#pragma mark
#pragma mark -------- Dealloc Methods --------

-(void)dealloc
{
    self.allArray = nil;// 非深拷贝数组，不能removeAllObject
    self.myIndexPath = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [super viewDidUnload];
}

@end
